package com.afd.ozblip.activity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.afd.ozblip.entity.CityEntity;
import com.afd.ozblip.net.HttpUtil;
import com.afd.ozblip.util.AsyncAction;
import com.afd.ozblip.util.AsyncLoadData;
import com.afd.ozblip.util.Constants;
import com.afd.ozblip.util.ParseJson;
import com.afd.ozblip.view.MyLetterListView;
import com.afd.ozblip.view.MyLetterListView.OnTouchingLetterChangedListener;
import com.j256.ormlite.dao.Dao;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

/**
 * 城市列表
 * 
 * @author sy
 * 
 */
public class CityListActivity extends BaseActivity {
	private BaseAdapter adapter;
	private ListView mCityLit;
	private TextView overlay;
	private MyLetterListView letterListView;
	private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
	private String[] sections;// 存放存在的汉语拼音首字母
	private Handler handler;
	private OverlayThread overlayThread;
	private SQLiteDatabase database;
	private OzBlipApplication myApp;
	private List<CityEntity> mCityNames;
	private LinearLayout cityGpsLayout;

	private Dao<CityEntity, Integer> cityDao;
	// 城市搜索控件
	private EditText searchEt;
	private String searchStr;

	private WindowManager windowManager;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.city_list);
		// 启动返回功能
		toBack();
		mCityLit = (ListView) findViewById(R.id.city_list);
		letterListView = (MyLetterListView) findViewById(R.id.cityLetterListView);
		alphaIndexer = new HashMap<String, Integer>();
		handler = new Handler();
		overlayThread = new OverlayThread();
		initOverlay();
		// 初始化搜索框
		this.searchEt = (EditText) findViewById(R.id.et_search_city);
		this.cityGpsLayout = (LinearLayout) findViewById(R.id.ll_city_gps);
		// 初始化APP
		this.myApp = (OzBlipApplication) getApplication();
		try {
			this.cityDao = myApp.getDBHelper().getDao(CityEntity.class);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		setListeners();
		// 获取数据
		requestAllCityData();
	}

	/**
	 * 设置监听
	 */
	public void setListeners() {
		View.OnClickListener cityClick = new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				switch (v.getId()) {
				case R.id.ll_city_gps:
					Intent indexIntent = new Intent(CityListActivity.this,
							IndexActivity.class);
					indexIntent.putExtra(IndexActivity.INTENT_TAB_CHANGE, 0);
					commonNowCityName = "重庆";
					// 根据城市获取地区列表
					commonRequestAreaListData();
					finish();
					break;

				default:
					break;
				}
			}
		};
		this.searchEt
				.setOnEditorActionListener(new TextView.OnEditorActionListener() {

					@Override
					public boolean onEditorAction(TextView v, int actionId,
							KeyEvent event) {
						searchStr = searchEt.getText().toString();
						if (alphaIndexer != null) {
							int position = alphaIndexer.get(searchStr);
							mCityLit.setSelection(position);
						}
						return false;
					}
				});
		letterListView
				.setOnTouchingLetterChangedListener(new LetterListViewListener());
		mCityLit.setOnItemClickListener(new CityListOnItemClick());
		this.cityGpsLayout.setOnClickListener(cityClick);
	}

	// TODO 获取添加商家数据
	/**
	 * 获取城市列表数据
	 */
	private void requestAllCityData() {
		AsyncLoadData ald = new AsyncLoadData(this, "加载中...",
				new AsyncAction() {

					@Override
					public void doLoad() throws Exception {
						// 获取提交参数
						Map<String, Object> addDishParamMap = new HashMap<String, Object>();
						// 发送请求
						byte[] bCity = HttpUtil.requestByPost(
								CityListActivity.this, Constants.CITY_LIST_API,
								addDishParamMap);
						if (bCity != null) {
							mCityNames = new ParseJson()
									.parseCityListJson2(bCity);
						}
					}

					@Override
					public void loadEnd() throws Exception {
						// // 将城市数据存储到数据库
						// try {
						// AndroidDatabaseConnection conn = new
						// AndroidDatabaseConnection(
						// myApp.getDBHelper().getWritableDatabase(), true);
						// cityDao.setAutoCommit(conn, false);
						// // cityDao.create(newBusinessInfo);
						// conn.commit(null);
						// cityDao.commit(conn);
						// } catch (Exception e) {
						// }
						setAdapter(mCityNames);
					}

				});
		ald.execute(0);

	}

	/**
	 * 从数据库获取城市数据
	 * 
	 * @return
	 */
	private ArrayList<CityEntity> getCityNames() {
		ArrayList<CityEntity> names = new ArrayList<CityEntity>();
		Cursor cursor = database.rawQuery(
				"SELECT * FROM T_City ORDER BY NameSort", null);
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			CityEntity cityModel = new CityEntity();
			cityModel.setCityName(cursor.getString(cursor
					.getColumnIndex("CityName")));
			cityModel.setNameSort(cursor.getString(cursor
					.getColumnIndex("NameSort")));
			names.add(cityModel);
		}
		return names;
	}

	/**
	 * 城市列表点击事件
	 * 
	 * @author sy
	 * 
	 */
	class CityListOnItemClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int pos,
				long arg3) {
			CityEntity cityModel = (CityEntity) mCityLit.getAdapter().getItem(
					pos);
			Intent indexIntent = new Intent(CityListActivity.this,
					IndexActivity.class);
			indexIntent.putExtra(IndexActivity.INTENT_TAB_CHANGE, 0);
			commonNowCityName = cityModel.getCityName();
			startActivity(indexIntent);
			// 根据城市获取地区列表
			commonRequestAreaListData();
			finish();
		}

	}

	/**
	 * 为ListView设置适配器
	 * 
	 * @param list
	 */
	private void setAdapter(List<CityEntity> list) {
		if (list != null) {
			// 加入热门城市
			List<CityEntity> hotCity = getHotCitys();
			list.addAll(0, hotCity);
			adapter = new ListAdapter(this, list);
			mCityLit.setAdapter(adapter);
		}

	}

	private List<CityEntity> getHotCitys() {
		List<CityEntity> hotCity = new ArrayList<CityEntity>();
		try {
			CityEntity city1 = new CityEntity();
			city1.setCityName("上海");
			city1.setNameSort("热门");
			hotCity.add(city1);
			CityEntity city2 = new CityEntity();
			city2.setCityName("北京");
			city2.setNameSort("热门");
			hotCity.add(city2);
			CityEntity city3 = new CityEntity();
			city3.setCityName("广州");
			city3.setNameSort("热门");
			hotCity.add(city3);
			CityEntity city4 = new CityEntity();
			city4.setCityName("深圳");
			city4.setNameSort("热门");
			hotCity.add(city4);
			CityEntity city5 = new CityEntity();
			city5.setCityName("重庆");
			city5.setNameSort("热门");
			hotCity.add(city5);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return hotCity;
	}

	/**
	 * ListViewAdapter
	 * 
	 * @author sy
	 * 
	 */
	private class ListAdapter extends BaseAdapter {
		private LayoutInflater inflater;
		private List<CityEntity> list;

		public ListAdapter(Context context, List<CityEntity> list) {

			this.inflater = LayoutInflater.from(context);
			this.list = list;
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[list.size()];

			for (int i = 0; i < list.size(); i++) {
				// 当前汉语拼音首字母
				// getAlpha(list.get(i));
				String currentStr = list.get(i).getNameSort();
				// 上一个汉语拼音首字母，如果不存在为“ ”
				String previewStr = (i - 1) >= 0 ? list.get(i - 1)
						.getNameSort() : " ";
				if (!previewStr.equals(currentStr)) {
					String name = list.get(i).getNameSort();
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
			}

		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			return list.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.city_list_item, null);
				holder = new ViewHolder();
				holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.name.setText(list.get(position).getCityName());
			String currentStr = list.get(position).getNameSort();
			String previewStr = (position - 1) >= 0 ? list.get(position - 1)
					.getNameSort() : " ";
			if (!previewStr.equals(currentStr)) {
				holder.alpha.setVisibility(View.VISIBLE);
				holder.alpha.setText(currentStr);
			} else {
				holder.alpha.setVisibility(View.GONE);
			}
			return convertView;
		}

		private class ViewHolder {
			TextView alpha;
			TextView name;
		}

	}

	// 初始化汉语拼音首字母弹出提示框
	private void initOverlay() {
		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.city_overlay, null);
		overlay.setVisibility(View.INVISIBLE);
		WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
				WindowManager.LayoutParams.TYPE_APPLICATION,
				WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
						| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
				PixelFormat.TRANSLUCENT);
		windowManager = (WindowManager) this
				.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
	}

	private class LetterListViewListener implements
			OnTouchingLetterChangedListener {

		@Override
		public void onTouchingLetterChanged(final String s) {
			if (alphaIndexer.get(s) != null) {
				int position = alphaIndexer.get(s);
				mCityLit.setSelection(position);
				overlay.setText(sections[position]);
				overlay.setVisibility(View.VISIBLE);
				handler.removeCallbacks(overlayThread);
				// 延迟一秒后执行，让overlay为不可见
				handler.postDelayed(overlayThread, 800);
			}
		}

	}

	// 设置overlay不可见
	private class OverlayThread implements Runnable {

		@Override
		public void run() {
			overlay.setVisibility(View.GONE);
		}

	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		windowManager.removeView(overlay);
	}

}